package com.bolt.report.engine.query;

import com.bolt.common.utils.JacksonUtil;
import com.bolt.common.utils.StrUtil;
import com.bolt.report.definition.DataSetDefinition;
import com.bolt.report.engine.BRDataSource;
import com.bolt.report.engine.CollectionDataSource;
import com.bolt.report.exception.ReportException;
import com.fasterxml.jackson.databind.JsonNode;

import java.util.List;
import java.util.Map;

public class JSONQueryExecute implements QueryExecute {
    private DataSetDefinition dataSetDefinition;


    public JSONQueryExecute(DataSetDefinition dataSetDefinition) {
        this.dataSetDefinition = dataSetDefinition;
    }

    @Override
    public BRDataSource createBRDataSource() {
        if (StrUtil.isNotEmpty(dataSetDefinition.getJsonData())) {
            try {
                JsonNode jsonObject = JacksonUtil.getObjectMapper().readTree(dataSetDefinition.getJsonData());
                List<Map> data = JacksonUtil.toList(jsonObject.get("data").toString(), Map.class);
                return new CollectionDataSource(data);
            } catch (Exception ex) {
                throw new ReportException(ex);
            }
        } else {
            throw new ReportException("JSON DATA IS EMPTY");
        }
    }

    @Override
    public List<?> queryData() {
        return ((CollectionDataSource) createBRDataSource()).getData();
    }


}